package tw.raybird.walker.officereader;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;



/**
 * 讀取巨大文字檔案用。避免記憶體洩漏(memory leak)
 * 參考:http://code.hammerpig.com/how-to-read-really-large-files-in-java.html
 * The entire file is never read into memory, so it should be able to handle files of any size
 * @author raybird
 *
 */
public class BigFile implements Iterable<String>, Closeable {

	private BufferedReader _reader;

	public BigFile(File file,String encoding) throws Exception {
		_reader = new BufferedReader(new InputStreamReader(new FileInputStream (file), encoding ));
	}
	
	public BigFile(String filePath) throws Exception {
		_reader = new BufferedReader(new FileReader(filePath));
	}
	
	public Iterator<String> iterator()
    {
		 return new FileIterator();
    }

	private class FileIterator implements Iterator<String> {
		private String _currentLine;

		public boolean hasNext() {
			try {
				_currentLine = _reader.readLine();
			} catch (Exception ex) {
				_currentLine = null;
				ex.printStackTrace();
			}

			return _currentLine != null;
		}

		public String next() {
			return _currentLine;
		}

		public void remove() {
		}
	}

	@Override
	public void close() throws IOException {
		Util.close(_reader);
	}
}
